﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using EKAABSInformationManagement.Models;
using EKAABSInformationManagement.Service;

namespace EKAABSInformationManagement.Controllers
{
    public class HomeController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        if (common.isUserInRole(model.UserName, "admin"))
                        {
                            return RedirectToAction("Index", "Member");
                        }
                        else if (common.isUserInRole(model.UserName, "member"))
                        {
                            return RedirectToAction("Index", "CustomerInfo");
                        }
                        else
                        {
                            throw new HttpException(401, "未经认证的用户");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码不正确。");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
